package com.bdqn.ch06.controller;

import com.bdqn.ch06.entity.User;
import com.bdqn.ch06.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Resource
    UserService userService;

    @GetMapping(value = "/login")
    public String login() {
        return "login";
    }

    @PostMapping(value = "/dologin")
    public String dologin(@RequestParam(value = "usrName") String usrName,
                          @RequestParam(value = "usrPassword") String usrPassword,
                          Model model,
                          HttpSession session) {
        User user = userService.findByUserNameBiz(usrName);
        if (user == null) {
            model.addAttribute("msg", "用户名不存在");
            return "login";
        } else {
            if (!user.getUsrPassword().equals(usrPassword)) {
                model.addAttribute("msg", "密码错误");
                return "login";
            } else {
                session.setAttribute("sessionuser", user);
                return "main";
            }
        }
    }
}
